package com.chapter.sample.juc.tl;

import lombok.Synchronized;

import java.util.concurrent.CountDownLatch;

class MovieTicket {
    int num = 50;

    public synchronized void saleTicket() {
        if (num > 0) {
            System.out.println(Thread.currentThread().getName() + " 卖出第：" + (num--));
        } else {
            System.out.println("卖完了");

        }

    }
}

class House {
    ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
    public void saleHouse(){
        Integer count = threadLocal.get();
        count++;
        threadLocal.set(count);
        //threadLocal.remove();
    }
}

public class ThreadLocalDemo {

    public static void main(String[] args) {
        MovieTicket movieTicket = new MovieTicket();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                for (int j = 0; j < 50; j++) {
                    movieTicket.saleTicket();

                }
            }).start();
        }

        House house = new House();
        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                house.saleHouse();
            }
            System.out.println(house.threadLocal.get());
        }).start();

        new Thread(()->{
            for (int i = 1; i <= 5; i++) {
                house.saleHouse();
            }
            System.out.println(house.threadLocal.get());
        }).start();

        new Thread(()->{
            for (int i = 1; i <= 6; i++) {
                house.saleHouse();
            }
            System.out.println(house.threadLocal.get());
        }).start();
    }
}
